#include "uthreads.hh"
#include <stdio.h>
#include<iostream>
#include <unistd.h>
#include <sys/time.h>

#define SECOND 1000000

void f( void )
{


    //printf("b\n");
    //int a=1;    printf("f: switching\n");

    //fprintf(stderr,"%d\n",a);
    //printf("c\n");
    int i=0;
    while(1) {
    	thread_sync(1,2);
    	thread_sleep(thread_gettid(),1000);
        ++i;
        printf("in f (%d)\n",i%50);

		//thread_sleep(thread_gettid(),2000);

        //usleep(SECOND);
        thread_sync(1,2);
    }

}

void g( void )
{
    int i=0;
    while(1){
    	thread_sleep(thread_gettid(),1000);
        ++i;
        printf("in g (%d)\n",i%23);
        thread_sync(1,2);
        thread_sync(1,2);
    }
}


void simple() {
	std::cout << "function `simple` is running in thread.id=" << thread_gettid() << std::endl;
	thread_terminate(thread_gettid());
}

void simple_sync() {
	std::cout << "function `simple_sync` is running in thread.id=" << thread_gettid() << std::endl;
	thread_sync(1,2);
	std::cout << "Thread.id=" << thread_gettid() << " Woke up." << std::endl;
	thread_terminate(thread_gettid());
}

bool asleep=true;
void sleeper() {
	std::cout << "Sleep ID is :" << thread_gettid() << std::endl;
	std::cout << "thread is going to sleep" << std::endl;
	thread_sleep(thread_gettid(),5000);
	std::cout << "Thread after sleep call" << std::endl;
	asleep=false;
	thread_terminate(thread_gettid());
}

int main() {
	thread_lib_init();
	
	/*std::cout << "** Basic test **" << std::endl << std::endl;
	
	std::cout << "Back from thread " << thread_spawn(simple) << std::endl;
	std::cout << "Back from thread " << thread_spawn(simple) << std::endl;
	
	
	std::cout << "** Simple Sync test **" << std::endl << std::endl;
	
	thread_spawn(simple_sync);
	std::cout << "Back to main." << std::endl;
	thread_spawn(simple_sync);
	std::cout << "Back to main." << std::endl;


	std::cout << "** sleep test **" << std::endl << std::endl;
	thread_spawn(sleeper);
	while(asleep) {}
	std::cout << "sleeper woke up" << std::endl;
	*/
	std::cout << "** sleep SECOND test **" << std::endl << std::endl;
	//thread_spawn(sleeper);
	thread_spawn(f);
	thread_spawn(g);
	while(1){}
	thread_terminate(0);
	
	std::cout << "If you can see this you have a bug!" << std::endl;
	return 0;
}
